###
 # @Author: Logan.Li
 # @Gitee: https://gitee.com/attacker
 # @email: admin@attacker.club
 # @Date: 2025-02-10 22:07:30
 # @LastEditTime: 2025-02-10 22:07:42
 # @Description: 
###
# 创建任务目录
sudo mkdir -p /opt/task

# 写入脚本内容
sudo tee /opt/task/check_nexus.sh > /dev/null <<'EOF'
#!/bin/bash

CONTAINER_NAME="nexus"
LOG_FILE="/var/log/nexus_monitor.log"

container_status=$(docker inspect -f '{{.State.Status}}' $CONTAINER_NAME 2>/dev/null)

if [[ "$container_status" != "running" ]]; then
    echo "$(date '+%F %T') - [$CONTAINER_NAME] 状态异常 (当前状态: ${container_status:-容器不存在})，正在尝试恢复..." | tee -a $LOG_FILE
    
    if docker start $CONTAINER_NAME > /dev/null 2>&1; then
        echo "$(date '+%F %T') - [$CONTAINER_NAME] 成功重启" | tee -a $LOG_FILE
    else
        echo "$(date '+%F %T') - [$CONTAINER_NAME] 重启失败！请手动检查！" | tee -a $LOG_FILE >&2
    fi
else
    echo "$(date '+%F %T') - [$CONTAINER_NAME] 运行正常" >> $LOG_FILE
fi
EOF

# 设置执行权限
sudo chmod +x /opt/task/check_nexus.sh

# 添加cron任务
(crontab -l 2>/dev/null; echo "* * * * * /opt/task/check_nexus.sh") | crontab -
# 查看任务列表
crontab -l